<template>
	<view class="container">
		<!-- 顶部状态栏 -->
		<view class="status-bar">
			<view class="driver-status">
				<text class="status-text">接单状态</text>
				<switch :checked="isWorking" @change="toggleWorkStatus" color="#1B6EF3" />
			</view>
			<view class="today-income">
				<text class="income-label">今日收入</text>
				<text class="income-value">¥{{todayIncome}}</text>
			</view>
		</view>

		<!-- 待抢订单列表 -->
		<scroll-view class="order-list" scroll-y>
			<view class="order-item" v-for="(order, index) in orderList" :key="index" @tap="grabOrder(order)">
				<view class="order-header">
					<text class="order-type">{{order.type}}</text>
					<text class="order-price">¥{{order.price}}</text>
				</view>
				<view class="order-address">
					<view class="address-item">
						<text class="address-label">起</text>
						<text class="address-text">{{order.startAddress}}</text>
					</view>
					<view class="address-item">
						<text class="address-label">终</text>
						<text class="address-text">{{order.endAddress}}</text>
					</view>
				</view>
				<view class="order-footer">
					<text class="distance">{{order.distance}}km</text>
					<button class="grab-btn" :disabled="!isWorking">抢单</button>
				</view>
			</view>
			<view class="no-more" v-if="noMore">没有更多订单了</view>
		</scroll-view>

		<!-- 添加自定义弹窗组件 -->
		<view class="custom-dialog" v-if="showDialog">
			<view class="dialog-mask" @tap="closeDialog"></view>
			<view class="dialog-content">
				<view class="dialog-title">派单提示</view>
				<view class="dialog-body">
					<view class="info-item">订单ID：{{dialogData.orderId}}</view>
					<view class="info-item">出发地：{{dialogData.startAddress}}</view>
					<view class="info-item">目的地：{{dialogData.endAddress}}</view>
					<view class="info-item">距离：{{dialogData.distance}}km</view>
				</view>
				<view class="dialog-footer">
					<view class="reject-btn" @tap="rejectOrder">拒单</view>
					<view class="confirm-btn" @tap="acceptOrder">接单</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	//引入qqmap  sdk
	import QQMapWX from '../../common/qqmap-wx-jssdk.js';
	import {
		getOrderList,
		orderTaking,
		driverStatus,
		getDriverOrders
	} from '@/request/api.js';
	import {rejectOrders} from '@/request/order.js'
	export default {
		data() {
			return {
				isWorking: false,
				todayIncome: '0.00',
				todayOrders: 0,
				monthOrders: 0,
				rating: '4.9',
				orderList: [],
				driverId:null,
				lat:11,
				long:11,
				page: 1,
				noMore: false,
				showDialog: false,
				dialogData: {
					orderId: '',
					startAddress: '',
					endAddress: '',
					distance: ''
				},
				distance:null,
				currentOrder: null,
			}
		},
		onLoad() {
			this.getLocation();
		},
		 onReady() {
		    this.fetchOrder();
			this.loadOrders();
			if (this.polling) clearInterval(this.polling); // 防止重复创建
			if (this.polls) clearInterval(this.polls);
		    this.polling = setInterval(this.fetchOrder, 5000);//5秒查询一次司机订单
			this.polls = setInterval(this.loadOrders, 5000);//5秒查询一次司机订单
		  },
		  beforeDestroy() {
		    if (this.polling) {
		      clearInterval(this.polling);
		      this.polling = null;
		    }
		    if (this.polls) {
		      clearInterval(this.polls);
		      this.polls = null;
		    }
		  },
		methods: {
			//查询系统派单
			async fetchOrder() {
			        getDriverOrders(this.driverId).then(res =>{
						console.log(res.data," 000021--d")
						if (res.data && res.data.orderId) {  
						  this.currentOrder = res.data;
						  this.distance = this.getMapDistance(this.currentOrder.startLat,this.currentOrder.startLng,this.currentOrder.endLat,this.currentOrder.endLng)
						  console.log("距离", this.distance);
						  console.log("收到新订单", this.currentOrder);
						  this.dialog()
						}
					}).catch(err => {
						console.log("查询系统订单失败！",err);
					})
			},
			toggleWorkStatus(e) {
				this.isWorking = e.detail.value;
				console.log(this.lat,this.long);

				if (this.isWorking) {
					const lat = this.lat * 1000000;
					const long = this.long * 1000000;
					const data = {
						driverId: this.driverId,
						driverX: lat,
						driverY: long,
						takingStatus: 1
					};
					console.log(data);
					driverStatus(data).then(res => {
						console.log(res);
						uni.showToast({
							title: '已开启接单',
							icon: 'success'
						})
					}).catch(err =>{
						console.log(err);
					})
				} else {
					const data = {
						driverId: this.driverId,
						takingStatus: 0,
					}
					driverStatus(data).then(res => {
						console.log(res);
						uni.showToast({
							title: '已暂停接单',
							icon: 'none'
						})
					}).catch(err =>{
						console.log(err);
					})
				}
			},
			// 加载订单列表
			loadOrders() {
				this.orderList = [];
				const user = uni.getStorageSync("userInfo");
				this.driverId = user.driverId;
				// console.log(user.driverId);
				getOrderList(user.driverId).then(res => {
					console.log(res.data,111111111111);
					if(res.data.length == 0){
						console.log(1111111199)
						
						return
					}
					//终点和起点的坐标
					const mockOrders = res.data.map((item, index) => ({
						orderId: item.orderId,
						type: '普通订单',
						price: item.price,
						startAddress: item.startAddress,
						endAddress: item.endAddress,
						distance: this.getMapDistance(item.startLat/ 1_000_000.0,item.startLng/ 1_000_000.0,item.endLat/ 1_000_000.0,item.endLng/ 1_000_000.0),
					}));
					this.orderList = mockOrders
					console.log(this.orderList);
				}).catch(err => {
					console.log(err);
				})

			},
			// 抢单
			grabOrder(order) {
				if (!this.isWorking) {
					uni.showToast({
						title: '请先开启接单状态',
						icon: 'none'
					})
					return
				}
				// console.log(order);
				const tripOrder = {
					orderId: order.orderId,
					driverId: uni.getStorageSync("userInfo").driverId,
					price: order.price
				}
				// console.log(tripOrder);
				uni.showModal({
					title: '确认抢单',
					content: `是否接单从${order.startAddress}到${order.endAddress},\n订单金额为¥${order.price}的订单？`,
					success: (res) => {
						if (res.confirm) {
							console.log(res.confirm);
							orderTaking(tripOrder).then(suc => {
								console.log(suc);
								if (suc.data == "抢单成功！") {

									uni.showToast({
										title: suc.data,
										icon: '抢单成功'
									})
									uni.navigateTo({
										url:"/pages/goUser/goUser"
									})
								} else {
									uni.showToast({
										title: suc.message,
										icon: 'error'
									})
								}
							}).catch(err => {
								console.log(err);
							})
						}
					}
				})
			},
			goToSettings() {
				uni.navigateTo({
					url: '/pages/setting/setting'
				});
			},
			//进行经纬度转换为距离的计算
			Rad(d) {
				return d * Math.PI / 180.0; //经纬度转换成三角函数中度分表形式。
			},
			/*
			 计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
			 默认单位km
			*/
			getMapDistance(lat1, lng1, lat2, lng2) {
				// console.log("in getMap")
				// console.log(lat1)
				var radLat1 = this.Rad(lat1);
				var radLat2 = this.Rad(lat2);
				var a = radLat1 - radLat2;
				var b = this.Rad(lng1) - this.Rad(lng2);
				var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
					Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
				s = s * 6378.137; // EARTH_RADIUS-地球半径;
				s = Math.round(s * 10000) / 10000; //输出为公里
				s = s.toFixed(1);
				//s=s.toFixed(2);
				console.log(s,11111111111111111111111111111);
				return s;
			},
			//获得司机当前位置
			getLocation() {
				console.log("111222");
				//使用定位api
				this.qqmapsdk = new QQMapWX({
					key: 'YYEBZ-FORCG-OEPQO-QE3GI-FW6SK-3JBTR'
				});
				//获得当前的位置信息
				const that = this;
				uni.getLocation({
					type: "gcj02",
					success(res) {
						console.log(res);
						that.lat = res.latitude;
						that.long =res.longitude;
						//this.long = res.longitude;
						console.log(that.lat, that.long)
					},
					fail(err) {
						console.log(err);
					}
				})
				console.log(that.lat, that.long)
			},
			//弹窗弹出系统派单信息
			dialog() {
				this.dialogData = {
					orderId: this.currentOrder.orderId,
					startAddress: this.currentOrder.startAddress,
					endAddress: this.currentOrder.endAddress,
					distance: this.distance 
				}
				this.showDialog = true;
			},
			closeDialog() {
				this.showDialog = false;
			},
			//拒绝接单
			rejectOrder() {
				console.log(this.dialogData,21313131414)
				this.showDialog = false;
				rejectOrders(this.dialogData).then(res => {
					console.log(res);
					if(res.data == "拒单上限"){
						uni.showToast({
							title: '拒单上限',
							icon: 'error'
						})
					}else{
						uni.showToast({
							title: '拒单成功',
							icon: 'success'
						})
					}
					
				}).catch(err=>{
					console.log(err);
				})
				
			},
			acceptOrder() {
				this.showDialog = false;
			
				orderTaking(this.currentOrder).then(res=>{
					
					console.log(res);
					if (res.data == "抢单成功！") {
						uni.showToast({
							title: '已接受订单',
							icon: 'success'
						})
						uni.navigateTo({
							url:"/pages/goUser/goUser"
						})
					} else {
						uni.showToast({
							title: suc.message,
							icon: 'error'
						})
					}
					
				}).catch(err =>{
					console.log(err);
				})
				
			}
		}
	}
</script>

<style>
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 200rpx;
		/* 为底部统计栏和导航栏留出空间 */
	}

	.status-bar {
		background-color: #1B6EF3;
		padding: 40rpx 30rpx;
		color: #fff;
	}

	.driver-status {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.status-text {
		font-size: 32rpx;
	}

	.today-income {
		text-align: center;
	}

	.income-label {
		font-size: 28rpx;
		opacity: 0.8;
	}

	.income-value {
		font-size: 48rpx;
		font-weight: bold;
		margin-top: 10rpx;
		display: block;
	}

	/* 订单列表样式 */
	.order-list {
		height: calc(100vh - 400rpx);
		padding: 20rpx 0rpx;
	}

	.order-item {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 30rpx 40rpx;
		margin-bottom: 20rpx;
	}

	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		padding: 0 10rpx;
	}

	.order-type {
		font-size: 28rpx;
		color: #666;
	}

	.order-price {
		font-size: 36rpx;
		color: #FF3B30;
		font-weight: bold;
	}

	.order-address {
		background-color: #f8f8f8;
		padding: 30rpx 40rpx;
		border-radius: 8rpx;
		margin-bottom: 20rpx;
	}

	.address-item {
		display: flex;
		align-items: center;
		margin-bottom: 10rpx;
	}

	.address-item:last-child {
		margin-bottom: 0;
	}

	.address-label {
		width: 40rpx;
		height: 40rpx;
		line-height: 40rpx;
		text-align: center;
		background-color: #1B6EF3;
		color: #fff;
		border-radius: 50%;
		font-size: 24rpx;
		margin-right: 10rpx;
	}

	.address-text {
		font-size: 28rpx;
		color: #333;
		flex: 1;
	}

	.order-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 20rpx;
	}

	.distance {
		font-size: 24rpx;
		color: #666;
	}

	.grab-btn {
		background-color: #1B6EF3;
		color: #fff;
		font-size: 28rpx;
		padding: 12rpx 60rpx;
		border-radius: 30rpx;
		margin: 0;
		min-width: 160rpx;
		text-align: center;
	}

	.grab-btn[disabled] {
		background-color: #ccc;
	}

	.no-more {
		text-align: center;
		color: #999;
		font-size: 24rpx;
		padding: 20rpx 0;
	}

	/* 订单统计样式 */
	.order-stats {
		position: fixed;
		bottom: 100rpx;
		left: 0;
		right: 0;
		display: flex;
		justify-content: space-around;
		background-color: #fff;
		padding: 20rpx 0;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.stat-item {
		text-align: center;
	}

	.stat-value {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		display: block;
	}

	.stat-label {
		font-size: 24rpx;
		color: #666;
		margin-top: 10rpx;
	}

	/* 底部导航栏样式 */
	.bottom-nav {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		background-color: #fff;
		display: flex;
		justify-content: space-around;
		align-items: center;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.nav-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.nav-item image {
		width: 48rpx;
		height: 48rpx;
		margin-bottom: 6rpx;
	}

	.nav-item text {
		font-size: 22rpx;
		color: #666;
	}

	.nav-item.active text {
		color: #1B6EF3;
	}

	.custom-dialog {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 999;
	}
	
	.dialog-mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.6);
	}
	
	.dialog-content {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 80%;
		background: #FFFFFF;
		border-radius: 12rpx;
		overflow: hidden;
	}
	
	.dialog-title {
		padding: 30rpx;
		text-align: center;
		font-size: 32rpx;
		font-weight: bold;
		border-bottom: 1rpx solid #EEEEEE;
	}
	
	.dialog-body {
		padding: 30rpx;
	}
	
	.info-item {
		padding: 20rpx 0;
		font-size: 28rpx;
		color: #333;
		border-bottom: 1rpx solid #EEEEEE;
	}
	
	.info-item:last-child {
		border-bottom: none;
	}
	
	.dialog-footer {
		padding: 20rpx;
		display: flex;
		justify-content: space-around;
		border-top: 1rpx solid #EEEEEE;
	}
	
	.confirm-btn, .reject-btn {
		display: inline-block;
		padding: 20rpx 60rpx;
		border-radius: 8rpx;
		font-size: 28rpx;
		width: 200rpx;
		text-align: center;
	}
	
	.confirm-btn {
		background: #1B6EF3;
		color: #FFFFFF;
	}
	
	.reject-btn {
		background: #FFFFFF;
		color: #666666;
		border: 1rpx solid #DDDDDD;
	}
</style>